<template>
    <div class="login">
        <div class="log">
            <img :src="systemData.pic" alt="">
            <div class="logi">
                <p class="p1">{{systemData.name}} | 商城</p>
                <p class="p2">{{systemData.brandname}}</p>
            </div>
        </div>
        <div v-if="pageState">
            <div class="inmn">
                <div class="item ste">
                    <p class="p2 fullp">中国大陆</p>
                </div>
                <div class="item ste">
                    <p class="p2 l">+86</p>
                    <div style="width: 2px;height: 100%;background: #f5f5f5"></div>
                    <input placeholder="请输入手机号码"
                           class="full1"
                           type="number"
                           pattern="[0-9]*"
                           onkeypress='return( /[\d]/.test(String.fromCharCode(event.keyCode) ) )'
                           v-model="phone"
                    >
                    <div class="statecss" v-show="statephone">
                        <p v-text="txtphone"></p>
                        <svg class="icon" aria-hidden="true">
                            <use :xlink:href="stateicon"></use>
                        </svg>
                    </div>
                </div>
            </div>
            <div class="inmn" style="margin-top: 2vw">
                <div class="item2">
                    <div class="int">
                        <input placeholder="请输入验证码"
                               pattern="[0-9]*"
                               type="number"
                               v-model="code"
                        >
                        <div class="statecss" v-show="statecode">
                            <p v-text="txtcode"></p>
                            <svg class="icon" aria-hidden="true">
                                <use :xlink:href="stateicon2"></use>
                            </svg>
                        </div>
                    </div>
                    <div class="r">
                        <p class="p4" :class="" @click="getCode">
                            {{codetxt}}
                        </p>
                    </div>
                </div>
            </div>
            <p class="p3">该注册手机号还将用于太空e家同步身份</p>
        </div>
        <div v-else>
            <div class="inmn">

                <div class="item ste">
                    <p class="p2 l">输入密码</p>
                    <div style="width: 2px;height: 100%;background: #f5f5f5"></div>
                    <input placeholder="6-16位字母与数字的组合"
                           class="full1"
                           type="password"
                           v-model="password"
                           @blur="isPass"
                    >
                </div>
                <div class="item ste">
                    <p class="p2 l">确认密码</p>
                    <div style="width: 2px;height: 100%;background: #f5f5f5"></div>
                    <input placeholder="6-16位字母与数字的组合"
                           class="full1"
                           type="password"
                           v-model="passwordSure"
                           @blur="isPass2"
                    >
                </div>
            </div>
            <div class="mi-ste">
                <div class="statecs2" v-show="passSure">
                    <p>不一致</p>
                    <svg class="icon" aria-hidden="true">
                        <use :xlink:href="stateicon"></use>
                    </svg>
                </div>
            </div>
        </div>
        <!--<div class="sync">-->
        <!--<div class="sync-1">-->
        <!--<p class="p1">代理商同步身份</p>-->
        <!--<p class="p2">我在其他系统是省市区代理</p>-->
        <!--</div>-->
        <!--<div class="syncs" @click="checkAgent">-->
        <!--<svg aria-hidden="true" class="icon">-->
        <!--<use :xlink:href="checkIcon"></use>-->
        <!--</svg>-->
        <!--</div>-->
        <!--</div>-->
        <div class="btn-db">
            <button-normal
                    widthPro="200"
                    heightPro="35"
                    :textBtn="textBtn"
                    color="#fff"
                    size="14"
                    @click.native="sure"
            ></button-normal>
        </div>
    </div>
</template>

<script>
    import API from '../request/api';
    import {Toast} from 'vant';
    import buttonNormal from '../components/common/buttonNormal';
    import ButtonNormalHollow from '../components/common/buttonNormalHollow';
    import {sysMixin} from '@/common/mixin';
    import {debounce} from '@/common/utils';
    import regular from '@/common/regular';
    import {commonMixin} from '@/common/mixin';


    export default {
        name: 'register',
        components: {ButtonNormalHollow, buttonNormal},
        mixins: [sysMixin, commonMixin],
        data() {
            return {
                dealshow: false,
                phone: '',
                code: '',
                password: '', // 密码
                passwordSure: '', //密码确认
                stateicon: '#icon-dui',
                stateicon2: '#icon-dui',
                txtphone: '', // 手机号校验文本
                statephone: false, //手机号状态文本显示
                stateCall: false, //手机号是否可以用
                codetxt: '获取', // 验证码校验文本
                txtcode: '',  // 验证码校验文本
                statecode: false, //验证码是否不对，true为不正确
                stateSendCode: true,
                pageState: true, // 是否是注册的第一种状态，校验手机号验证码
                statepass: false, //密码是否不一致，true为不一致
                textBtn: '下一步', // 按钮文本
                way: 4
                // isagent: 0,
            };
        },
        computed: {
            // checkIcon() {
            //     return this.isagent === 0 ? '#icon-dui' : '#icon-dui';
            // },
            passSure() {
                // 密码确认
                let regu = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
                if ((!regu.test(this.passwordSure) && this.password !== '') || this.passwordSure !== this.password) {
                    this.stateicon = '#icon-cuo';
                    return true;
                } else if (this.passwordSure == this.password) {
                    return false;
                }
            }
        },
        watch: {},
        methods: {
            // 监听具体数据变化，并做相应的处理
            checkPhone() {
                if (!regular.REGEX_CHINA_MOBILE.test(this.phone)) {
                    this.txtphone = '手机号不正确';
                    this.stateicon = '#icon-cuo';
                    this.statephone = true;
                } else {
                    this.request.post(API.signPhone, {phone: this.phone}).then((res) => {
                        console.log(res);
                        if (res.status == 1) {
                            // 可以注册
                            this.stateCall = true;
                            this.txtphone = '可以使用';
                            this.stateicon = '#icon-dui';
                        } else if (res.status == 0) {
                            //    已注册
                            this.stateCall = false;
                            this.txtphone = '已注册';
                            this.stateicon = '#icon-cuo';
                        }
                        this.statephone = true;
                    });

                    // this.stateSendCode = true;
                }
            },
            isPass() {
                //    密码校验
                let regu = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{6,16}$/;
                if (!regu.test(this.password)) {
                    Toast('密码需为6-16位字母加数字组合');
                    this.password = '';
                }
            },
            isPass2() {
                //    密码校验
                let regu = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
                if (!regu.test(this.passwordSure)) {
                    Toast('密码需为6-16位字母加数字组合');
                    this.passwordSure = '';
                }
            },
            async sure() {
                if (this.textBtn == '下一步') {
                    if (!this.phone) {
                        Toast('请先填写手机号');
                    } else if (!this.stateCall) {
                        Toast('该手机号已注册');
                    } else if (!this.code || this.stateSendCode) {
                        Toast('请先获取并填写验证码');
                    } else {
                        // 只验证短信吗
                        if (await this.selectCode()) {
                            this.pageState = false;
                            this.textBtn = '注册';
                        }
                    }
                } else {
                    if (this.passwordSure === this.password && this.password !== '') {
                        this.showGlobaLoading();
                        let data = {
                            phone: this.phone,
                            code: this.code,
                            password: this.password,
                            referrer: this.$store.state.login.refer.referid,
                            system: this.$store.state.login.system,
                            way: this.way
                        };
                        this.request.post(API.sign, data).then((res) => {
                            // 返回的数据直接登录了
                            this.$store.commit('setToken', res.token); // 本地存token
                            this.$store.commit('setTokenType', res.token_type || '1');
                            this.$store.commit('system', res.system);
                            // 注册成功，推购物车数据
                            if (this.$store.state.online.cart.cartList) {
                                this.request.post(API.onlineGetCartListPush, {
                                    cartList: this.$store.state.online.cart.cartList
                                }).then((res) => {
                                    this.$store.commit('addToCart_online', '');
                                }, (res) => {
                                });
                            }
                            // 然后获取userInfo
                            this.request.get(API.getUserInfo).then((res1) => {
                                // userinfo 本地存储
                                this.$store.commit('setUserInfo', res1);
                                //  更新tokenArray
                                let tokenArray = JSON.parse(localStorage.getItem('tokenArray'));
                                if (tokenArray) {
                                    // 原来有就更新
                                    tokenArray[res.system] = {token: res.token, userInfo: res1};
                                    this.$store.commit('setTokenArray', tokenArray);
                                } else {
                                    // 没有就新建本地tokenArray
                                    let tokenArrayFirst = {};
                                    tokenArrayFirst[res.system] = {token: res.token, userInfo: res1};
                                    this.$store.commit('setTokenArray', tokenArrayFirst);
                                }
                                this.hideGlobaLoading();
                                // this.$router.back();
                                if (this.$store.state.user.way == 'app') {
                                    // 扫app进入且注册
                                    this.$router.replace('app-code2');
                                } else {
                                    this.$router.push({
                                        name: 'front'
                                    });
                                }
                            });
                        }, (res) => {
                            this.hideGlobaLoading();
                        });
                    }
                }

            },
            deal() {
                this.dealshow = true;
            },
            getCode() {
                if (!this.phone || this.txtphone === '手机号不正确') {
                    Toast('请先填写手机号');
                } else if (!this.stateCall) {
                    Toast('该手机号已注册不能再次注册');
                } else {
                    let data = {
                        'phone': this.phone,
                        'type': 2
                    };
                    if (this.stateSendCode) {
                        this.request.post(API.getCode, data).then((res) => {
                            //    验证码发送成功
                            this.stateSendCode = false;
                            this.setTime();
                        });
                    }

                }

            },
            setTime() {
                //    倒计时
                let demo = 70;
                this.codetxt = demo;
                let setTer = setInterval(() => {
                    if (demo > 0) {
                        this.codetxt = demo;
                        demo--;
                    } else {
                        clearInterval(setTer);
                        this.codetxt = '获取';
                        this.stateSendCode = true;
                        this.txtphone = '';
                    }
                }, 1000);
            },
            // checkAgent() {
            //     //    代理商同步
            //     if (this.isagent === 0) {
            //         this.isagent = 1;
            //     } else {
            //         this.isagent = 0;
            //     }
            //     this.checkPhone();
            // },
            selectCode() {
                // 校验验证码正确
                return this.request.post(API.checkCode, {type: 2, code: this.code, phone: this.phone}).then((res) => {
                    if (res.status == 1) {
                        // 正确
                        return true;
                    } else if (res.status == 0) {
                        Toast('验证码错误');
                        return false;
                    }
                });
            }
        },
        beforeCreate() {
            // 可以在这加个loading事件，在加载实例时触发
            // 这个阶段实例的data、methods是读不到的
        },
        created() {
            this.$watch(
                'phone',
                debounce((newVal) => {
                    this.checkPhone();
                }, 100)
            );
            // 判断小程序还是web环境
            if (window.__wxjs_environment === 'miniprogram') {
                //     小程序
                this.way = 3;
            }
            // 初始化数据，如在这结束loading事件，异步ajax请求也适宜在这里调用
            // 实例创建后：这个阶段已经完成了数据观测(data observer)，属性和方法的运算， watch/event 事件回调。
            // mount挂载阶段还没开始，"el" 属性目前不可见，数据并没有在DOM元素上进行渲染
        },
        beforeMount() {
            // 相关的 render 函数首次被调用。
        },
        mounted() {
            window.addEventListener('focusout', () => {
                window.scrollTo(0, 0);
            });
            // 挂载元素，获取到DOM节点
            // el选项的DOM节点 被新创建的 vm的el 替换，并挂载到实例上去之后调用此生命周期函数。此时实例的数据在DOM节点上进行渲染
        },
        beforeUpdate() {
            // 数据更新时调用，但不进行DOM重新渲染，在数据更新时DOM没渲染前可以在这个生命函数里进行状态处理
        },
        updated() {
            //  如果对数据统一处理，在这里写上相应函数
        },
        beforeDestroy() {
            // 可以做一个确认停止事件的确认框
        },
        destroyed() {
            // Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，所有的事件监听器会被移除，所有的子实例也会被销毁
        }
    };

</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    @import '~assets/main.styl'
    .login {
        position relative
        box-sizing border-box
        background #f5f5f5
        width 100vw

        .log {
            height 30vw
            flex-x(center)
            padding-top 12vh

            img {
                width vw(66)
            }

            .logi {
                height 12vw
                flex-y(space-between, flex-start)
                padding-left 3vw
            }
        }

        .inmn {
            flex-y()
            margin 0 vw(15)
            border-radius main-radius
            background grayF

            .item {
                width 100%
                height vw(55)
                flex-x()

                .l {
                    flex 1.5
                    text-align center
                }

                .r {
                    flex 4
                    padding-left 20vw
                    box-sizing border-box
                }

                .fullp {
                    flex 1
                    text-align center
                    line-height vw(55)
                }

                .full {
                    flex 1
                    text-align center
                    height vw(25)
                    padding vw(10) 0
                }

                .full1 {
                    flex 4
                    text-align left
                    height vw(25)
                    padding vw(10) 0 vw(10) vw(60)
                }
            }

            .statecss {
                position absolute
                right vw(30)
                flex-x()

                .icon {
                    margin-left vw(15)
                    fill main-color
                }

                p {
                    word-vw(word14, main-color)
                }
            }

            .ste {
                border-bottom 1px solid gray5
            }

            .item2 {
                flex-x(space-between)
                height vw(55)
                flex-x()
                width 100%

                .int {
                    flex 4
                    flex-x()
                    padding-left vw(15)

                    input {
                        height vw(55)
                    }
                }

                .r {
                    flex 1
                    background main-color
                    border-radius 0 main-radius main-radius 0
                    height vw(55)
                    flex-x(center)
                }
            }
        }

        .mi-ste {
            padding 0 4vw
            flex-x(flex-end)
            height vw(24)

            .statecs2 {
                width 18vw
                flex-x(flex-end)
                right 3vw

                .icon {
                    margin-left vw(8)
                    fill main-color
                }

                p {
                    word-vw(word14, main-color)
                }
            }
        }

        .btn-db {
            position fixed
            background white
            width 100vw
            bottom 0
        }

        .p3 {
            line-height 1.4
            margin-top 5vw
            text-align center
        }
        @media (max-height: 400px) {
            .btn-db {
                display: none;
            }
        }
        input:

        :placeholder {
            color gray9
        }

        .sync {
            flex-x()
            padding 0 4vw
            margin-top 3vw
            height 10vw

            .sync-1 {
                .p1 {
                    word-vw(word14, gray3)
                    line-height 2
                }

                .p2 {
                    word-vw(word10, gray9)
                }
            }

            .icon {
                width vw(20)
                height vw(20)
            }
        }
    }

    .sure {
        background-color main-color
        position relative
        width 100vw
        text-align center
        height vw(50)
        line-height vw(50)
        left 0
        color grayF
    }
</style>
